<?php

namespace app\admin\controller\apply;

use app\common\model\CostBill;
use EasyWeChat\Factory;
use Exception;
use ba\Random;
use think\facade\Db;
use app\common\controller\Backend;
use app\admin\model\User as UserModel;
use app\admin\model\UserGroup;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class Bill extends Backend
{
    protected $model = null;

    protected $withJoinTable = ['user'];



    protected $quickSearchField = ['summary', 'amount', 'id'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new CostBill();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        foreach ($res as $re) {

            $re->photo = isset(json_decode($re['photos'],true)[0])?json_decode($re['photos'],true)[0]:'';
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $salt   = Random::build('alnum', 16);
            $passwd = $this->model->encryptPassword($data['password'], $salt);

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['salt']     = $salt;
                $data['password'] = $passwd;
                $result           = $this->model->save($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    /**
     * 重写select
     */
    public function select()
    {
        $this->request->filter(['strip_tags', 'trim']);

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        foreach ($res as $re) {

            $re->photo = json_decode($re['photos'],true)[0];
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    public function edit($id = null)
    {

        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {


            $data = $this->request->post();
           // print_r($data);
            if($data['status']==1){


                $config = [
                    'app_id' => 'wx56c979d82ef6e40d',
                    'secret' => '71b08c91f4f06acfa635249ae9ffb9f9',

                    // 下面为可选项
                    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                    'response_type' => 'array',

                    'log' => [
                        'level' => 'debug',
                        'file' => __DIR__.'/wechat.log',
                    ],
                ];
                $type_text=$this->request->get('type')==1?'今日中餐':'今日晚餐';
                //avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
                //city: ""
                //country: ""
                //gender: 0
                //language: ""
                //nickName: "微信用户"
                //province: ""
                $app = Factory::miniProgram($config);
                $value=\app\admin\model\User::find($row['user_id']);


                    $data = [
                        'template_id' => 'NI5Cg_BrAsVbteKwkaCUWzgYpyHiKbe4X15EHi2OBpo', // 所需下发的订阅模板id
                        'touser' => $value['openid'],     // 接收者（用户）的 openid
                        'page' => 'pages/mbook/billDetail?id='.$id,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                        'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                            'thing1' => [
                                'value' => $row['summary'],
                            ],
                            'thing2' => [
                                'value' => $value['nickname'],
                            ],
                            'amount3' => [
                                'value' => $row['amount'],
                            ],
                            'time4' => [
                                'value' =>date('Y-m-d H:i:s',$row['create_time']),
                            ],
                            'phrase5'=> [
                                'value' =>'通过',
                            ],
                        ],
                    ];

                    $r=$app->subscribe_message->send($data);
                   // print_r($r);

            }

            parent::edit($id);
        }




        $this->success('', [
            'row' => $row
        ]);
    }
}